#include "HttpPutRequest.h"
#include "Utils.h"

#include <sstream>
#include <iostream>
#include <stdlib.h>

#include "Poco/Net/HTTPClientSession.h"
#include "Poco/Net/HTTPRequest.h"
#include "Poco/Net/HTTPResponse.h"
#include "Poco/StreamCopier.h"
#include "Poco/Exception.h"

using Poco::Net::HTTPClientSession;
using Poco::Net::HTTPRequest;
using Poco::Net::HTTPResponse;
using Poco::Net::HTTPMessage;
using Poco::StreamCopier;
using Poco::Exception;

HttpPutRequest::HttpPutRequest(const string& serverAddress, unsigned short port, const string& path, vector<unsigned char> encoded)
{
	HTTPResponse response;
	HTTPClientSession session(serverAddress, port);
	HTTPRequest request(HTTPRequest::HTTP_PUT, path, HTTPMessage::HTTP_1_1);
    ostringstream hostStream;  
    hostStream << serverAddress << ":" << port;
    request.set("Host", hostStream.str());
    request.setContentType("image/jpg");
    
    request.setContentLength(encoded.size());

    ostream& ostr = session.sendRequest(request);
    
    for(unsigned int i=0;i<encoded.size();i++)
        ostr << encoded[i];
    
    istream& rs = session.receiveResponse(response);

    StreamCopier::copyToString(rs,this->response); // default bufferSize = 8192
	this->reason = response.getReason();
	this->statusCode = response.getStatus();
    
    if(this->statusCode != 200)
    {
        throw Exception(string("HttpPutRequest got status code other then 200 on path: ") + path);      
    }
    
}

unsigned int HttpPutRequest::getStatus()
{
	return this->statusCode;
}
string HttpPutRequest::getReason()
{
	return this->reason;
}

string HttpPutRequest::getResponse()
{
	return this->response;
}
